package xin.marcher.module.common.utils;

import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * 汉语拼音工具类
 */
@Slf4j
public class BopomofoUtil {

    /**
     * 汉字转换首拼
     *
     * @param target
     * @return
     */
    public static String initialsTransfer(String target) {
        char[] charArray = target.toCharArray();
        StringBuilder bopomofo = new StringBuilder();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        // 设置大小写格式
        defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        // 设置声调格式：
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        try {
            for (int i = 0; i < charArray.length; i++) {
                // 匹配中文,非中文转换会转换成null
                if (Character.toString(charArray[i]).matches("[\\u4E00-\\u9FA5]+")) {
                    String[] hanyuPinyinStringArray = PinyinHelper.toHanyuPinyinStringArray(charArray[i], defaultFormat);
                    if (hanyuPinyinStringArray != null) {
                        bopomofo.append(hanyuPinyinStringArray[0].charAt(0));
                    }
                }
            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            log.error("首拼转换异常", e);
        }
        return bopomofo.toString();
    }

}
